<template>
  <div class="home-container">
    <!-- 视频列表容器 -->
    <div 
      ref="containerRef"
      class="video-container"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
      @wheel="onWheel"
    >
      <!-- 视频项 -->
      <div
        v-for="(video, index) in videoStore.recommendVideos"
        :key="video.id"
        class="video-item"
        :class="{ 
          active: index === videoStore.currentVideoIndex,
          'slide-up': touchState.direction === 'up' && touchState.isDragging,
          'slide-down': touchState.direction === 'down' && touchState.isDragging
        }"
        :style="getVideoItemStyle(index)"
      >
        <!-- 视频播放器 -->
        <VideoPlayer
          :ref="el => setVideoPlayerRef(el, index)"
          :video-url="video.videoUrl"
          :cover-url="video.coverUrl"
          :autoplay="index === videoStore.currentVideoIndex"
          @play="onVideoPlay(video, index)"
          @pause="onVideoPause(video, index)"
          @canplay="onVideoCanPlay(video, index)"
        />
        
        <!-- 视频信息和交互区域 -->
        <VideoInfo
          :video="video"
          :video-index="index"
        />
        
        <!-- 右侧操作栏 -->
        <div class="action-panel">
          <!-- 头像 -->
          <div class="author-avatar" @click="goToUserProfile(video.author?.id)">
            <UserAvatar
              :user-id="video.author?.id"
              :avatar-url="video.author?.avatar"
              :username="video.author?.nickname"
              size="large"
              :clickable="true"
            />
          </div>
          
          <!-- 点赞 -->
          <div class="action-item like-action" :class="{ active: video.isLiked }" @click="handleLike(index)">
            <div class="action-icon">
              <HeartIcon 
                :size="32" 
                :filled="video.isLiked" 
                :color="video.isLiked ? '#fe2c55' : 'white'"
              />
            </div>
            <span class="action-count">{{ formatCount(video.likeCount) }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="videoStore.loading && videoStore.recommendVideos.length === 0" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">正在为您推荐精彩内容...</div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!videoStore.loading && videoStore.recommendVideos.length === 0" class="empty-container">
      <el-icon :size="80">
        <VideoPlay />
      </el-icon>
      <div class="empty-text">暂无精彩内容</div>
      <div class="empty-desc">刷新试试看吧~</div>
      <el-button type="primary" size="large" @click="refreshVideos">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>
    
    <!-- 滑动提示 -->
    <div v-if="showScrollTip" class="scroll-tip">
      <div class="tip-content">
        <el-icon :size="20"><ArrowUp /></el-icon>
        <span>上滑看下一个</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useVideoStore } from '@/stores/video'
import { useUserStore } from '@/stores/user'
import { throttle, formatCount } from '@/utils'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
import VideoInfo from '@/components/VideoInfo/index.vue'
import UserAvatar from '@/components/UserAvatar/index.vue'
import HeartIcon from '@/components/HeartIcon/index.vue'
import { ElMessage } from 'element-plus'
import {
  VideoPlay,
  Refresh,
  ArrowUp
} from '@element-plus/icons-vue'

const router = useRouter()
const videoStore = useVideoStore()
const userStore = useUserStore()

const containerRef = ref(null)
const videoPlayerRefs = ref(new Map())
const showScrollTip = ref(false)

// 触摸相关状态
const touchState = ref({
  startY: 0,
  currentY: 0,
  startX: 0,
  currentX: 0,
  isDragging: false,
  direction: null,
  startTime: 0,
  velocity: 0
})

// 设置视频播放器引用
const setVideoPlayerRef = (el, index) => {
  if (el) {
    videoPlayerRefs.value.set(index, el)
  } else {
    videoPlayerRefs.value.delete(index)
  }
}

// 获取视频项样式
const getVideoItemStyle = (index) => {
  const currentIndex = videoStore.currentVideoIndex
  const offset = (index - currentIndex) * 100
  
  // 添加滑动时的动态偏移
  let dynamicOffset = 0
  if (touchState.value.isDragging && touchState.value.direction) {
    const deltaY = touchState.value.currentY - touchState.value.startY
    const maxOffset = 30 // 最大偏移百分比
    dynamicOffset = Math.max(-maxOffset, Math.min(maxOffset, (deltaY / window.innerHeight) * 100))
  }
  
  return {
    transform: `translateY(${offset + dynamicOffset}vh)`,
    zIndex: index === currentIndex ? 10 : 1,
    transition: touchState.value.isDragging ? 'none' : 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
  }
}

// 触摸开始
const onTouchStart = (e) => {
  const touch = e.touches[0]
  touchState.value.startY = touch.clientY
  touchState.value.currentY = touch.clientY
  touchState.value.startX = touch.clientX
  touchState.value.currentX = touch.clientX
  touchState.value.isDragging = true
  touchState.value.direction = null
  touchState.value.startTime = Date.now()
  touchState.value.velocity = 0
}

// 触摸移动
const onTouchMove = (e) => {
  if (!touchState.value.isDragging) return
  
  const touch = e.touches[0]
  touchState.value.currentY = touch.clientY
  touchState.value.currentX = touch.clientX
  
  const deltaY = touchState.value.currentY - touchState.value.startY
  const deltaX = touchState.value.currentX - touchState.value.startX
  const deltaTime = Date.now() - touchState.value.startTime
  
  // 计算滑动速度
  touchState.value.velocity = Math.abs(deltaY) / deltaTime
  
  // 判断滑动方向（垂直滑动优先）
  if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 10) {
    e.preventDefault() // 阻止默认滚动行为
    
    if (!touchState.value.direction) {
      touchState.value.direction = deltaY > 0 ? 'down' : 'up'
    }
  } else if (Math.abs(deltaX) > 30) {
    // 水平滑动，不阻止默认行为
    return
  }
}

// 触摸结束
const onTouchEnd = () => {
  if (!touchState.value.isDragging) return
  
  const deltaY = touchState.value.currentY - touchState.value.startY
  const deltaTime = Date.now() - touchState.value.startTime
  const velocity = Math.abs(deltaY) / deltaTime
  
  // 根据滑动距离和速度判断是否切换视频
  const threshold = velocity > 0.5 ? 30 : 80 // 高速滑动降低阈值
  
  if (Math.abs(deltaY) > threshold) {
    if (deltaY > 0) {
      // 向下滑动，播放上一个视频
      switchToPreviousVideo()
    } else {
      // 向上滑动，播放下一个视频
      switchToNextVideo()
    }
  }
  
  // 重置触摸状态
  touchState.value.isDragging = false
  touchState.value.direction = null
  touchState.value.velocity = 0
}

// 鼠标滚轮事件
const onWheel = throttle((e) => {
  e.preventDefault()
  
  if (e.deltaY > 0) {
    // 向下滚动，播放下一个视频
    switchToNextVideo()
  } else {
    // 向上滚动，播放上一个视频
    switchToPreviousVideo()
  }
}, 300)

// 切换到上一个视频
const switchToPreviousVideo = () => {
  const currentPlayer = videoPlayerRefs.value.get(videoStore.currentVideoIndex)
  if (currentPlayer) {
    currentPlayer.pause()
  }
  
  const previousVideo = videoStore.toPreviousVideo()
  if (previousVideo) {
    playCurrentVideo()
  }
}

// 切换到下一个视频
const switchToNextVideo = async () => {
  const currentPlayer = videoPlayerRefs.value.get(videoStore.currentVideoIndex)
  if (currentPlayer) {
    currentPlayer.pause()
  }
  
  const nextVideo = await videoStore.toNextVideo()
  if (nextVideo) {
    playCurrentVideo()
  }
}

// 播放当前视频
const playCurrentVideo = async () => {
  await nextTick()
  const currentPlayer = videoPlayerRefs.value.get(videoStore.currentVideoIndex)
  if (currentPlayer) {
    currentPlayer.play()
  }
}

// 视频播放事件
const onVideoPlay = (video, index) => {
  // 记录观看
  if (userStore.isLoggedIn) {
    videoStore.viewVideo(video.id)
  }
  
  // 隐藏滑动提示
  if (showScrollTip.value) {
    showScrollTip.value = false
  }
}

// 视频暂停事件
const onVideoPause = (video, index) => {
  // 可以在这里添加暂停相关的逻辑
}

// 视频可播放事件
const onVideoCanPlay = (video, index) => {
  // 如果是当前视频且设置了自动播放，开始播放
  if (index === videoStore.currentVideoIndex) {
    const player = videoPlayerRefs.value.get(index)
    if (player) {
      player.play()
    }
  }
}

// 点赞处理
const handleLike = async (index) => {
  try {
    await videoStore.likeVideo(index)
    // 添加点赞动画效果
    const event = new CustomEvent('likeAnimation', { detail: { index } })
    document.dispatchEvent(event)
  } catch (error) {
    ElMessage.error('点赞失败，请重试')
  }
}

// 跳转到用户主页
const goToUserProfile = (userId) => {
  if (userId) {
    router.push(`/user/${userId}`)
  }
}

// 刷新视频
const refreshVideos = async () => {
  try {
    await videoStore.fetchRecommendVideos(true)
    if (videoStore.recommendVideos.length > 0) {
      playCurrentVideo()
    }
  } catch (error) {
    ElMessage.error('加载失败，请重试')
  }
}

// 键盘事件处理
const onKeyDown = (e) => {
  switch (e.key) {
    case 'ArrowUp':
      e.preventDefault()
      switchToPreviousVideo()
      break
    case 'ArrowDown':
      e.preventDefault()
      switchToNextVideo()
      break
    case ' ':
      e.preventDefault()
      const currentPlayer = videoPlayerRefs.value.get(videoStore.currentVideoIndex)
      if (currentPlayer) {
        currentPlayer.videoElement.click()
      }
      break
  }
}

// 组件挂载
onMounted(async () => {
  // 添加键盘事件监听
  window.addEventListener('keydown', onKeyDown)
  
  // 如果没有视频，加载推荐视频
  if (videoStore.recommendVideos.length === 0) {
    try {
      await videoStore.fetchRecommendVideos(true)
      if (videoStore.recommendVideos.length > 0) {
        // 延迟一下确保组件渲染完成
        setTimeout(() => {
          playCurrentVideo()
          // 显示滑动提示
          setTimeout(() => {
            showScrollTip.value = true
            setTimeout(() => {
              showScrollTip.value = false
            }, 3000)
          }, 1000)
        }, 100)
      }
    } catch (error) {
      ElMessage.error('加载视频失败')
    }
  } else {
    // 如果已有视频，播放当前视频
    nextTick(() => {
      playCurrentVideo()
    })
  }
})

// 组件卸载
onBeforeUnmount(() => {
  window.removeEventListener('keydown', onKeyDown)
  
  // 暂停所有视频
  videoPlayerRefs.value.forEach(player => {
    if (player) {
      player.pause()
    }
  })
})
</script>

<style lang="scss" scoped>
.home-container {
  width: 100vw;
  height: 100vh;
  background: $bg-dark;
  overflow: hidden;
  position: relative;
}

.video-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.video-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  
  &.active {
    z-index: 10;
  }
  
  // 滑动状态样式
  &.slide-up {
    transform: translateY(-10vh) !important;
  }
  
  &.slide-down {
    transform: translateY(10vh) !important;
  }
}

.action-panel {
  position: absolute;
  right: 12px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  z-index: 20;
  
  .author-avatar {
    cursor: pointer;
    transition: $transition-fast;
    
    &:hover {
      transform: scale(1.05);
    }
  }
  
  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    transition: $transition-fast;
    
    .action-icon {
      width: 48px;
      height: 48px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      transition: $transition-fast;
      backdrop-filter: blur(10px);
      
      &:hover {
        background: rgba(255, 255, 255, 0.2);
        transform: scale(1.1);
      }
    }
    
    .action-count {
      font-size: 12px;
      color: white;
      font-weight: 500;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
    }
    
    &.like-action.active {
      .action-icon {
        background: rgba(254, 44, 85, 0.2);
        color: $primary-color;
      }
      
      .action-count {
        color: $primary-color;
      }
    }
    
    &:hover {
      transform: scale(1.05);
    }
  }
}

.loading-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  
  .loading-spinner {
    width: 48px;
    height: 48px;
    border: 4px solid rgba(255, 255, 255, 0.1);
    border-top: 4px solid $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text {
    color: $text-white;
    font-size: 16px;
    font-weight: 500;
  }
}

.empty-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  text-align: center;
  
  .el-icon {
    color: $text-gray;
  }
  
  .empty-text {
    color: $text-white;
    font-size: 20px;
    font-weight: 600;
  }
  
  .empty-desc {
    color: $text-gray-light;
    font-size: 14px;
    margin-top: -12px;
  }
  
  .el-button {
    margin-top: 8px;
  }
}

.scroll-tip {
  position: absolute;
  bottom: 200px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 30;
  animation: fadeInUp 0.5s ease, fadeOut 0.5s ease 2.5s forwards;
  
  .tip-content {
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 12px 20px;
    border-radius: 25px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

// 禁用默认的拖拽和选择
.video-container {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  
  -webkit-touch-callout: none;
  -webkit-tap-highlight-color: transparent;
}

// 移动端适配
@media (max-width: 768px) {
  .action-panel {
    right: 8px;
    bottom: 100px;
    gap: 20px;
    
    .action-item .action-icon {
      width: 44px;
      height: 44px;
    }
  }
  
  .scroll-tip {
    bottom: 180px;
    
    .tip-content {
      padding: 10px 16px;
      font-size: 13px;
    }
  }
}
</style> 